document.addEventListener('DOMContentLoaded', function () {

    // --- 滚动监听，更新侧边栏激活状态 ---
    const sections = document.querySelectorAll('main section');
    const navLinks = document.querySelectorAll('.sidebar nav a');

    const observerOptions = {
        root: null, // 视口
        rootMargin: '0px',
        threshold: 0.3 // 30%可见时触发
    };

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                navLinks.forEach(link => {
                    link.classList.remove('active');
                    if (link.getAttribute('href').substring(1) === entry.target.id) {
                        link.classList.add('active');
                    }
                });
            }
        });
    }, observerOptions);

    sections.forEach(section => {
        observer.observe(section);
    });


    // --- 代码块复制功能 ---
    const copyButtons = document.querySelectorAll('.copy-btn');

    copyButtons.forEach(button => {
        button.addEventListener('click', () => {
            const pre = button.previousElementSibling;
            const code = pre.querySelector('code');
            const textToCopy = code.innerText;

            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalText = button.innerText;
                button.innerText = '已复制!';
                button.style.backgroundColor = '#d4edda'; // 绿色背景
                setTimeout(() => {
                    button.innerText = originalText;
                    button.style.backgroundColor = ''; // 恢复原状
                }, 2000);
            }).catch(err => {
                console.error('复制失败: ', err);
                const originalText = button.innerText;
                button.innerText = '复制失败';
                 button.style.backgroundColor = '#f8d7da'; // 红色背景
                setTimeout(() => {
                    button.innerText = originalText;
                    button.style.backgroundColor = '';
                }, 2000);
            });
        });
    });

}); 